﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlTypes;
using EasyCLRBase;
using EasyCLRBase.AssemblyExplorer;

namespace EasyCLRNetwork
{
    [Export(typeof(EasyCLRBase.IClrBase))]
    public class Scalar : ClrBase
    {
        [Microsoft.SqlServer.Server.SqlFunction(Name = "ext_net_web_request")]
        public static SqlString ClrWebRequest(
            SqlString uri, 
            SqlString userAgent, 
            SqlString method, 
            [ClrParameter(Result = "bit = 0")]SqlBoolean responseRequired)
        {
            SqlString result = String.Empty;
            System.Net.WebRequest request = System.Net.HttpWebRequest.Create(uri.Value);

            if (userAgent.IsNull == false)
                ((System.Net.HttpWebRequest)request).UserAgent = userAgent.Value;

            request.Method = (method.IsNull ? "GET" : method.Value);
            if (responseRequired.IsNull == true || responseRequired.IsFalse == true)
            {
                request.BeginGetResponse(null, null);
                result = "No result available. Request send asynchronious.";
            }
            else
            {
                using (var response = new System.IO.StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8))
                {
                    result = response.ReadToEnd();
                }
            }

            return result;
        }
    }
}
